import { useEffect, useRef, useState } from 'react';

import mapImg from '@/assets/img/map.jpg';

import { PointVo, Status, statusColor } from './drawMap';

const CanvasRecord = (props: {
  dataSource: PointVo[];
  onClick: (arg0: { name: string; x: number; y: number; width: number; height: number }) => void;
  scale?: number;
  style?: React.CSSProperties;
}) => {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const [texts, setTexts] = useState<
    {
      name: string;
      x: number;
      y: number;
      width: number;
      height: number;
    }[]
  >([]);

  useEffect(() => {
    const canvas = canvasRef.current as HTMLCanvasElement | null;
    const ctx = canvas!.getContext('2d');
    initCanvas(ctx!, canvas!);
  }, [props.dataSource]);

  //Canvas画布，重新绘制巡检点位和箭头连线
  const initCanvas = (ctx: CanvasRenderingContext2D, canvas: HTMLCanvasElement) => {
    if (canvas) {
      canvas.width = 700;
      canvas.height = 430;

      const img = new Image();
      img.src = encodeURI(mapImg);

      img.onload = function () {
        // 将图片画到canvas上面上去！
        const currentContent = ctx!.getImageData(0, 0, canvas.width, canvas.height);

        ctx!.putImageData(currentContent, 0, 0);

        // canvas.style.backgroundSize = `${canvas.width}px ${canvas.height}px`;
        // canvas.style.backgroundImage = 'url("' + img.src + '")'; //改动这行
        ctx!.drawImage(img, 0, 0, canvas.width, canvas.height);

        ctx!.font = '20px 楷体';
        ctx!.textAlign = 'center';
        ctx!.textBaseline = 'middle';

        const rightDraw = [
          '中控室',
          '外排间',
          '加药间',
          '风机间',
          '脱泥间',
          '预处理',
          '雨水池',
          '一体化',
          '生化系统'
        ];

        props.dataSource.forEach((item: any) => {
          return drawPoint(ctx!, item);
        });

        props.dataSource.forEach((item: { name: string; x: number; y: number }, index: number) => {
          if (index < props.dataSource.length - 1) {
            if (rightDraw.includes(item.name)) {
              //右侧点，箭头指向下方
              drawArrow(
                ctx!,
                item.x,
                item.y - 10,
                props.dataSource[index + 1].x,
                props.dataSource[index + 1].y + 10
              );
            } else {
              //左侧点，箭头指向上方
              drawArrow(
                ctx!,
                item.x,
                item.y + 10,
                props.dataSource[index + 1].x,
                props.dataSource[index + 1].y - 10
              );
            }
          }
        });
      };

      // ctx!.strokeStyle = 'red';
      // ctx!.strokeRect(10, 10, 100, 100);
    }
  };

  //画巡检点位
  const drawPoint = (
    ctx: CanvasRenderingContext2D,
    item: { name: string; x: number; y: number; status: Status }
  ) => {
    // 测量文本宽度
    const textMetrics = ctx!.measureText(item.name);
    const textWidth = textMetrics.width + 5;
    const textHeight = 30; // 近似高度

    // 保存文本信息
    setTexts((prev) => [
      ...prev,
      {
        name: item.name,
        x: item.x - textWidth / 2,
        y: item.y + textHeight / 2,
        width: textWidth,
        height: textHeight
      }
    ]);

    // 绘制椭圆背景
    ctx.beginPath();
    ctx.ellipse(item.x, item.y, textWidth / 2, textHeight / 2, 0, 0, 2 * Math.PI);

    const color =
      item.status === Status.异常
        ? statusColor[Status.异常].rgba
        : item.status === Status.已巡检
          ? statusColor[Status.已巡检].rgba
          : statusColor[Status.待巡检].rgba;
    ctx.fillStyle = color;
    ctx.fill();

    //绘制文本、描边
    // ctx.lineWidth = 2;
    // ctx.strokeStyle = 'red';
    // ctx.strokeText(item.name, item.x, item.y);
    ctx!.fillStyle = 'black';

    ctx!.fillText(item.name, item.x, item.y);

    // 绘制文本边界框（用于调试）
    // ctx.strokeStyle = 'rgba(0, 0, 0, 0.4)';
    // ctx.strokeRect(x - textWidth / 2, y - textHeight / 2, textWidth, textHeight);
  };

  //画箭头
  const drawArrow = (
    ctx: CanvasRenderingContext2D,
    fromX: number,
    fromY: number,
    toX: number,
    toY: number,
    headLength = 15
  ) => {
    // 绘制线条
    ctx.beginPath();
    ctx.moveTo(fromX, fromY);
    ctx.lineTo(toX, toY);
    ctx.lineWidth = 3;
    ctx.strokeStyle = '#00C19F';
    ctx.stroke();

    // 计算箭头角度
    const angle = Math.atan2(toY - fromY, toX - fromX);

    // 绘制箭头头部
    ctx.beginPath();
    ctx.moveTo(toX, toY);

    const x = toX - headLength * Math.cos(angle - Math.PI / 6);
    const y = toY - headLength * Math.sin(angle - Math.PI / 6);
    ctx.lineTo(x, y);
    // ctx!.moveTo(toX, toY);

    ctx!.lineTo(
      toX - headLength * Math.cos(angle + Math.PI / 6),
      toY - headLength * Math.sin(angle + Math.PI / 6)
    );

    ctx!.closePath();
    ctx!.stroke();
    ctx.fillStyle = '#00C19F';
    ctx!.fill();
  };

  // 检测点击是否在文本范围内
  const isPointInText = (
    x: number,
    y: number,
    textX: number,
    textY: number,
    textWidth: number,
    textHeight: number
  ) => {
    return x >= textX && x <= textX + textWidth && y >= textY - textHeight && y <= textY;
  };

  //点击事件
  const onClick = (event: { clientX: number; clientY: number }) => {
    // 点击事件处理
    const rect = canvasRef.current!.getBoundingClientRect();
    const x = event.clientX - rect.left;
    const y = event.clientY - rect.top;

    // const rect = canvas.getBoundingClientRect();
    // const x = event.clientX - rect.left;
    // const y = event.clientY - rect.top;
    // console.log('X coordinate: ' + x + ', Y coordinate: ' + y);

    // 检查每个文本区域
    for (const text of texts) {
      if (isPointInText(x, y, text.x, text.y, text.width, text.height)) {
        props.onClick(text);
      }
    }
  };

  return (
    <canvas
      ref={canvasRef}
      width="700"
      height="430"
      style={{ cursor: 'pointer', ...props.style }}
      onClick={onClick}
    ></canvas>
  );
};

export default CanvasRecord;
